package com.spotalog.server.service.rest;

import static com.spotalog.shared.service.rest.Endpoints.QueryParams.ALTERED;
import static com.spotalog.shared.service.rest.Endpoints.QueryParams.CREATED;
import static com.spotalog.shared.service.rest.Endpoints.QueryParams.CURSOR;
import static com.spotalog.shared.service.rest.Endpoints.QueryParams.KEYWORDS;
import static com.spotalog.shared.service.rest.Endpoints.QueryParams.LIMIT;
import static com.spotalog.shared.service.rest.Endpoints.QueryParams.RADIUS;
import static com.spotalog.shared.service.rest.Endpoints.Spots.ENDPOINT;
import static com.spotalog.shared.service.rest.Endpoints.Spots.QueryParams.TYPE;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.spotalog.server.service.SpotService;
import com.spotalog.shared.model.Radius;
import com.spotalog.shared.model.Spot;
import com.spotalog.shared.model.SpotType;
import com.spotalog.shared.service.rest.Envelope;

@Path(ENDPOINT)
public class SpotResource extends RestService<Spot> {
	private final SpotService spotService;
	private static final Splitter SPLIT = Splitter.on(',').trimResults()
			.omitEmptyStrings();

	@Inject
	SpotResource(SpotService spotService) {
		super(spotService);
		this.spotService = spotService;
	}

	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Envelope<Spot> querySpots(@QueryParam(KEYWORDS) String keywords,
			@QueryParam(RADIUS) Radius radius, @QueryParam(TYPE) SpotType type,
			@QueryParam(ALTERED) Date altered,
			@QueryParam(CREATED) Date created,
			@QueryParam(CURSOR) String cursorString,
			@QueryParam(LIMIT) int limit) {
		List<String> keywordList = Lists.newArrayList(SPLIT.split(Strings
				.nullToEmpty(keywords)));
		return this.spotService.queryWithCursor(radius, keywordList, type,
				altered, created, safeCursor(cursorString), limit);
	}
}
